package com.ty.xiaoyu.util;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.Base64;

@Slf4j
public class Base64Util {

    public static String getType(String base64Message) {
        return base64Message.split(":")[1].split("/")[0];
    }

    public static String getSuffix(String base64Message) {
        return base64Message.split("/")[1].split(";")[0];
    }
    
    public static byte[] decodeToBytes(String base64Data) {
        String data = base64Data.replace("\n", "").replace("\r", "");
        Base64.Decoder decoder = Base64.getDecoder();
        byte[] bytes = decoder.decode(data);
        return bytes;
    }

    /**
     * 保存图片
     * @param image
     * @param filePath
     * @return
     * @throws IOException
     */
    public static String saveImage(String image, String filePath) throws IOException {
        if (image.length() > 60){
            log.debug("image: " + image.substring(0, 60));
        } else {
            log.debug("image: " + image);
            
        }
        String base64Message = image.split("\\.")[0];
        String type = Base64Util.getType(base64Message);
        String fileName = null;
        if ("img".equals(type) || "image".equals(type)) {
            String base64Data = image.split("\\.")[1];// 获得图片的字节数据
            byte[] bytes = Base64Util.decodeToBytes(base64Data);
            fileName = FileUtil.getRandomFileName() + "." + Base64Util.getSuffix(base64Message);
            // 保存用户头像
            try {
                log.debug("filePath + fileName: " + filePath + fileName);
                FileUtil.saveFile(filePath + fileName, bytes);
            } catch (IOException e) {
                log.error(MyTimeUtil.nowTime() + "=== register 保存图片出错 ===");
                throw e;
            }
        } else {
            log.error(MyTimeUtil.nowTime() + "=== register 上传文件不是图片 ===");
            throw new IOException("不是图片文件");
        }
        return fileName;
    }
}
